package cn.pet.service.manage.auth;


import cn.pet.service.manage.entity.api.Result;
import cn.pet.service.manage.utils.JsonUtil;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;

@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {

    /**
     * 此类继承Spring Security的AuthenticationEntryPoint类，并重写其commence。
     * 它拒绝每个未经身份验证的请求并发送错误代码401
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param e
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
//        Result result = new Result(false, 401, "请先登录");
        httpServletResponse.setContentType("application/json");
        httpServletResponse.setCharacterEncoding("UTF8");
        httpServletResponse.setStatus(401);
        httpServletResponse.getWriter().print(JsonUtil.toJson(Result.error(401,"请先登录")));
    }

}